<template>
  <el-dialog title="新增员工" :visible="showDialog" @close="btnCancel">
    <!-- 表单 -->
    <el-form ref="ruleForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="formData.username" style="width:50%" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="formData.mobile" style="width:50%" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker v-model="formData.timeOfEntry" style="width:50%" placeholder="请选择入职时间" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="formData.formOfEmployment" style="width:50%" placeholder="请选择">
          <el-option
            v-for="item in employeeEnum.hireType"
            :key="item.id"
            :value="item.id"
            :label="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="formData.workNumber" style="width:50%" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-input v-model="formData.departmentName" style="width:50%" placeholder="请选择部门" @focus="getpartments" @blur="onblue" />

        <!-- 部门树形图开始 -->
        <el-tree v-if="showTree" v-loading="loading" :data="treeData" :props="{label:'name'}" default-expand-all class="deptTree" @node-click="selectNode" />
        <!-- 部门树形图结束 -->

      </el-form-item>
      <el-form-item label="转正时间">
        <el-date-picker v-model="formData.correctionTime" style="width:50%" placeholder="请选择转正时间" />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import employeeEnum from '@/api/constant/employees'
import { department } from '@/api/department'
import { addRole, getEmployee } from '@/api/employees'
import { listToTreeData } from '@/utils'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    //   校验手机号码
    const validateMobile = async(rule, val, callback) => {
      const { rows } = await getEmployee({ page: 1, size: 100000 })
      //   校验整个数组是否有该手机号码重复
      const isRepeat = rows.some(item => item.mobile === val)
      console.log(isRepeat)
      if (isRepeat) {
        callback(new Error('手机号码已存在'))
      } else {
        callback()
      }
    }
    return {
      employeeEnum,
      // 表单数据
      treeData: [], // 定义数组接收树形数据
      showTree: false, // 控制树形的显示或者隐藏
      loading: false, // 控制树的显示或者隐藏进度条
      formData: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      rules: {
        username: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }, {
          min: 1, max: 4, message: '用户姓名为1-4位'
        }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }],
        formOfEmployment: [{ required: true, message: '聘用形式不能为空', trigger: 'blur' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        departmentName: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        timeOfEntry: [{ required: true, message: '入职时间', trigger: 'blur' }]
      }

    }
  },

  //   函数
  methods: {
    //   关闭窗口
    btnCancel() {
      // 清空数据
      this.formData = {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      }
      // 调用自身的方法清空数据
      this.$refs.ruleForm.resetFields()
      this.$emit('btnCancel')
    },

    //  封装请求函数
    async  getpartments() {
      this.showTree = true
      this.loading = true
      const res = await department()
      // console.log('部门数据', res)
      // 调用函数
      this.treeData = listToTreeData(res.depts, '')
      this.loading = false
    },

    // 当我点击哪个部门时，把数据赋值给表单的v-model
    selectNode(e) {
      console.log(e.name)
      this.formData.departmentName = e.name
      this.showTree = false
    },

    // 失去焦点时
    onblue() {
      setTimeout(() => {
        this.showTree = false
      }, 100)
    },

    // 点击确定时，发送数据
    async  btnOK() {
      console.log(this.formData)
      // 捕获异常
      try {
        //   1.校验数据
        await this.$refs.ruleForm.validate()
        // 2.发送数据
        await addRole(this.formData)
        // 3.提醒用户
        this.$message.success('添加成功')
        // 4.关闭弹窗
        this.btnCancel()
        // 5.刷新数据
        this.$emit('updata')
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>

<style lang='scss'>

.deptTree {
  width: 50%;
  border: 1px solid #ccc;
  height: 200px;
  overflow: auto;
  position: absolute;
  z-index: 9;
}
</style>
